//RuleApp是一套开源免费的客户端代码，如果您通过任何收费渠道下载到了此代码，则可以认为你被忽悠了。
//正式版下载地址：https://ext.dcloud.net.cn/plugin?id=6909
//github内测版地址：https://github.com/buxia97/RuleApp
// var API_URL = 'https://story.hhui.top/';
// var API_URL = 'http://localhost:8081/';
var API_URL = 'https://ys.hhui.top/';
var IMG_HOST = "http://yss.hhui.top";


import {
	localStorage
} from '../store/mp-storage/mp-storage/index.js'

module.exports = {
	imgHost: function() {
		return IMG_HOST;
	},

	execH5login: function() {
		return API_URL + "admin/user/login"
	},
	// 首页
	fetchHomeIndex: function() {
		return API_URL + "app/list"
	},
	fetchHomeGoodsMore: function() {
		// 首页更多商品
		return API_URL + "app/next";
	},
	fetchCategoryList: function() {
		// 分类列表
		return API_URL + "app/categoryList";
	},
	fetchCategoryGoods: function() {
		// 分类商品列表
		return API_URL + "app/categoryGoodsList"
	},
	fetchCustorInfos: function() {
		// 客服列表
		return API_URL + "app/customer"
	},
	execUserLogin: function() {
		// 用户登录
		return API_URL + "app/user/login"
	},
	execUserLogout: function() {
		// 用户登出
		return API_URL + "app/user/logout"
	},
	execUpdateUserInfo: function() {
		// 用户信息保存
		return API_URL + "app/user/updateInfo"
	},
	execUpdateUserAvatar: function() {
		return API_URL + "app/user/updateAvatar"
	},
	fetchUserInfo: function() {
		// 获取用户信息
		return API_URL + "app/user/info"
	},
	fetchUserAddressList: function() {
		// 获取用户地址列表
		return API_URL + "app/address/list"
	},
	fetchUserMainAddress: function() {
		// 获取用户地址列表
		return API_URL + "app/address/main"
	},
	execAddUserAddress: function() {
		// 新增用户地址
		return API_URL + "app/address/add"
	},
	execUpdateUserAddress: function() {
		// 更新地址
		return API_URL + "app/address/update"
	},
	execDeleteUserAddress: function() {
		return API_URL + "app/address/delete"
	},
	execUpdateDefaultUserAddress: function() {
		return API_URL + "app/address/markDefault"
	},
	fetchGoodsInfo: function() {
		return API_URL + "app/goods/detail";
	},
	execUploadImg: function() {
		return API_URL + "img/upload"
	},
	execDeleteOrder: function() {
		return API_URL + "app/order/delete"
	},
	execPayOrder: function() {
		// 去支付
		return API_URL + "app/order/toPay"
	},
	execPaying: function() {
		// 支付成功
		return API_URL + "app/order/markPay"
	},
	execAddOrder: function() {
		// 添加订单
		return API_URL + "app/order/add"
	},
	execUpdateOrder: function() {
		// 更新订单
		return API_URL + "app/order/update"
	},
	fetchOrderList: function() {
		// 订单列表
		return API_URL + "app/order/list"
	},
	fetchOrderDetail: function() {
		return API_URL + "app/order/detail"
	},
	fetchImgUploadToken: function() {
		// 图片上传的token获取
		return API_URL + "img/token"
	},

	cachePrefix_dailyChallenge() {
		// 每日挑战
		return `daily_challenge`;
	},
	isLogined() {
		// 判断用户是否已经登录
		let cacheUser = this.getUserInfoFromCache();
		if (cacheUser && cacheUser.userId && cacheUser.logined) {
			return true;
		}
		return false;
	},
	getUserInfoFromCache() {
		// 获取用户缓存
		return this.getFromCache('userInfo');
	},
	putUserInfoIntoCache(userInfo) {
		// 更新用户缓存
		this.saveToCache('userInfo', userInfo, 1, '-');
	},
	clearUserInfo() {
		// 移除用户缓存
		this.invalidCache('userInfo');
	},
	/**
	 * @param {Object} key 缓存 key
	 * @param {Object} val 缓存 val
	 * @param {Object} expire 有效期 毫秒单位
	 */
	saveToCache(key, val, expire, unit = 'ms') {
		let now = new Date().getTime();
		if (unit == 'ms') {
			now += expire;
		} else if (unit == 's') {
			now += expire * 1000;
		} else if (unit == 'm') {
			now += expire * 60_000;
		} else if (unit == 'h') {
			now += expire * 3600_000;
		} else if (unit == 'd') {
			now += expire * 24 * 3600_000;
		} else if (unit == '-') {
			// 无有效期，这里直接存储五十年
			now += 1 * 24 * 3600_000 * 360 * 50;
		}
		let data = {
			'data': val,
			'expireAt': now
		}
		localStorage.setItem(key, JSON.stringify(data));
	},
	/**
	 * 只获取有效的数据
	 * @param {Object} key
	 */
	getFromCache(key) {
		let now = new Date().getTime();
		let ans = localStorage.getItem(key)
		if (ans) {
			ans = JSON.parse(ans);
			if (now > ans['expireAt']) {
				return null;
			} else {
				// 有效
				return ans['data']
			}
		} else {
			console.log('缓存未命中->', key);
			return
		}
	},
	/**
	 * 返回待状态的缓存结果
	 * @param {Object} key
	 */
	getFromCacheWithExpireState(key) {
		let now = new Date().getTime();
		let ans = localStorage.getItem(key)
		if (ans) {
			ans = JSON.parse(ans);
			return {
				'legal': now <= ans['expireAt'],
				'data': ans['data']
			}
		} else {
			console.log('缓存未命中->', key);
			return {
				'legal': false,
				'data': null
			}
		}
	},
	invalidCache(key) {
		localStorage.removeItem(key);
	},
	IsNull(obj) {
		return (obj != null && obj != undefined);
	},
	randomHexColor() { //随机生成十六进制颜色
		var hex = Math.floor(Math.random() * 16777216).toString(16); //生成ffffff以内16进制数
		while (hex.length < 6) { //while循环判断hex位数，少于6位前面加0凑够6位
			hex = '0' + hex;
		}
		return '#' + hex; //返回‘#'开头16进制颜色
	},
	//获取日期
	formatDate(datetime) {
		datetime = parseInt(datetime)
		if (datetime < 17189618680) {
			datetime = datetime * 1000;
		}
		var datetime = new Date(parseInt(datetime));
		// 获取年月日时分秒值  slice(-2)过滤掉大于10日期前面的0
		var year = datetime.getFullYear(),
			month = ("0" + (datetime.getMonth() + 1)).slice(-2),
			date = ("0" + datetime.getDate()).slice(-2),
			hour = ("0" + datetime.getHours()).slice(-2),
			minute = ("0" + datetime.getMinutes()).slice(-2);
		//second = ("0" + date.getSeconds()).slice(-2);
		// 拼接
		var result = year + "-" + month + "-" + date + " " + hour + ":" + minute;
		// 返回
		return result;
	},
	//移除数据中的空对象
	removeObjectEmptyKey(json) {
		var value;
		for (var key in json) {
			if (json.hasOwnProperty(key)) {
				value = json[key];
				if (value === undefined || value === '' || value === null) {
					delete json[key]
				}
			}
		}
		return json;
	},
	goTo(url) {
		// 跳转
		console.log('统一跳转执行: ', url);
		if (url && (url.startsWith("owl") || url.startsWith("http"))) {
			// h5跳转
			window.location.href = url;
			// app内部跳转
			// plus.runtime.openWeb(banner.url);
			// #ifdef APP-PLUS
			plus.runtime.openWeb(banner.url);
			// #endif
		} else {
			uni.navigateTo({
				'url': url
			})
		}
	},
	toLoginPage() {
		// #ifdef MP-WEIXIN
		this.goTo("/pages/user/login/login")
		// #endif
		// #ifndef MP-WEIXIN
		this.goTo("/pages/public/login")
		// #endif
	},
	goBack() {
		// 通过判断当前页面的页面栈信息，是否有上一页进行返回，如果没有则跳转到首页
		const pages = getCurrentPages()
		console.log('返回上一级 -->', pages);
		if (pages && pages.length > 0) {
			const firstPage = pages[0]
			if (pages.length == 1 && (!firstPage.route || firstPage.route != '/pages/index/index')) {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			} else {
				uni.navigateBack({
					delta: 1
				})
			}
		} else {
			uni.reLaunch({
				url: '/pages/index/index'
			})
		}
	},
	today() {
		let today = new Date();
		let year = today.getFullYear() % 2000;
		let mon = (1 + today.getMonth());
		let day = today.getDate();
		if (mon < 10) {
			mon = `0${mon}`
		}
		if (day < 10) {
			day = `0${day}`
		}
		return `${year}${mon}${day}`;
	},
	timeToImgPath(timestamp) {
		let date;
		if (timestamp) {
			if (timestamp && timestamp < 171810817300) {
				timestamp = timestamp * 1000
			}
			date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
		} else {
			date = new Date();
		}
		let Y = date.getFullYear() + '';
		let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '';
		let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '';
		let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + '';
		let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + '';
		let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
		return Y + M + D + "_" + h + m + s + "_"
	},
	order_status(status, payStatus) {
		if (payStatus == 5) {
			return "支付中";
		} else if(payStatus == 20) {
			return "退款中"
		} else if (payStatus == 30) {
			return "已退款"
		} else if (payStatus == 100) {
			return "支付失败";
		}
		
		if (status == 100) {
			return "已取消"
		}

		if (status == 10 || payStatus != 10) {
			return "待付款"
		} else if (status == 11) {
			return "拼团中"
		} if (status == 15) {
			return "待打印"
		} else if (status == 20) {
			return "待发货"
		} else if (status == 25) {
			return "待收货"
		} else if (status == 30) {
			return "已签收"
		} else if (status == 35) {
			return "已完成"
		} else if (status == 80) {
			return "已退款"
		} 
	},
	
	cm2px(size) {
		return parseFloat(((size + 0.4) * 600 / 2.54).toFixed(2))
	},
	imgToBlob(url) {
		if (typeof url === 'string') {
			// #ifdef H5
			return this.base64ToBlob(url)
			// #endif
		}

		return url
	},
	h5blobUrlToObj(url) {
		return new Promise((resolve, reject) => {
			const xhr = new XMLHttpRequest()
			xhr.open('GET', url, true)
			xhr.responseType = 'blob'
			xhr.onload = function onload(e) {
				console.log('进入这里了', this.response, this.status, e);
				if (this.status == 200) {
					const Blob = this.response
					resolve(Blob)
				} else {
					reject(this.status, e)
				}
			}
			xhr.send()
		})
	},
	base64ToBlob(dataURI) {
		var base64Arr = dataURI.split(",");
		var imgtype = "";
		var base64String = "";
		if (base64Arr.length > 1) {
			//如果是图片base64，去掉头信息
			base64String = base64Arr[1];
			imgtype = base64Arr[0].substring(
				base64Arr[0].indexOf(":") + 1,
				base64Arr[0].indexOf(";")
			);
		}
		// 将base64解码
		var bytes = atob(base64String);
		//var bytes = base64;
		var bytesCode = new ArrayBuffer(bytes.length);
		// 转换为类型化数组
		var byteArray = new Uint8Array(bytesCode);

		// 将base64转换为ascii码
		for (var i = 0; i < bytes.length; i++) {
			byteArray[i] = bytes.charCodeAt(i);
		}

		// 生成Blob对象（文件对象）
		return new Blob([bytesCode], {
			type: imgtype
		});
	},
	// 压缩图片
	// path：base64 格式图片 
	// obj：文件压缩后对象width， height， quality(0-1)
	// callback：容器或者回调函数
	/* 利用canvas数据化图片进行压缩 */
	photoCompress(path, obj, callback) {
		var img = new Image()
		img.src = path
		img.onload = function() {
			var that = this // 指到img
			// 默认按比例压缩
			var w = that.width
			var h = that.height
			var scale = w / h
			w = obj.width || w
			h = obj.height || (w / scale)
			var quality = 0.92 // 默认图片质量为0.7
			// 生成canvas
			var canvas = document.createElement('canvas')
			var ctx = canvas.getContext('2d')
			// 创建属性节点
			var anw = document.createAttribute('width')
			anw.nodeValue = w
			var anh = document.createAttribute('height')
			anh.nodeValue = h
			canvas.setAttributeNode(anw)
			canvas.setAttributeNode(anh)
			ctx.drawImage(that, 0, 0, w, h)
			// 图像质量
			if (obj.quality && obj.quality > 0 && obj.quality <= 1) {
				quality = obj.quality
			}
			// quality值越小，所绘制出的图像越模糊
			var base64 = canvas.toDataURL('image/png', quality)
			// 回调函数返回base64的值
			callback(base64)
		}
	},
	/**
	 * 图片url链接转base64
	 * @param {String} url 图片链接
	 * @returns 转base64后的值或者报错信息
	 */
	imgUrlToBase64(url) {
		// #ifdef MP-WEIXIN
		return new Promise((resolve, reject) => {
			uni.getFileSystemManager().readFile({
				filePath: url, //参数path:图片相对路径
				encoding: 'base64', 
				success: res => {
					let base64 = res.data
					resolve(base64)
				},
				fail: err => {
					console.log(err)
					reject(err)
				}
			})
		})
		// #endif
		// #ifdef H5
		  return new Promise((resolve, reject) => {
			if (!url) {
			  reject('请传入url内容');
			}
		
			if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(url)) {
			  // 图片地址
			  const image = new Image();
			  // 设置跨域问题
			  image.setAttribute('crossOrigin', 'anonymous');
			  // 图片地址
			  image.src = url;
			  image.onload = () => {
				const canvas = document.createElement('canvas');
				const ctx = canvas.getContext('2d');
				canvas.width = image.width;
				canvas.height = image.height;
				ctx.drawImage(image, 0, 0, image.width, image.height);
				// 获取图片后缀
				const ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
				// 转base64
				const dataUrl = canvas.toDataURL(`image/${ext}`);
				resolve(dataUrl || '');
			  }
			} else {
			  // 非图片地址
			  reject('非(png/jpe?g/gif/svg等)图片地址');
			}
		  });
	  // #endif
	},

	buildUploadImgName(source, imgType) {
		let path = this.buildUploadImgPath() + "_" + source + "." + imgType;
		return "ys/" + path + fileName;
	},
	buildUploadImgPath() {
		// 构建图片上传文件名
		let today = new Date();
		let year = today.getFullYear() % 2000;
		let mon = (1 + today.getMonth());
		let day = today.getDate();
		if (mon < 10) {
			mon = `0${mon}`
		}
		if (day < 10) {
			day = `0${day}`
		}

		let user = this.getUserInfoFromCache();
		let uid = 0
		let path;
		if (user) {
			uid = user.userId;
			if (uid == 4) {
				// 测试用户
				path = "0/" + year + mon + day + "/"
			} else {
				path = uid + "/" + year + mon + "/" + day
			}
		} else {
			path = "0/" + year + mon + day + "/"
		}

		let h = (today.getHours() < 10 ? '0' + today.getHours() : today.getHours()) + '';
		let m = (today.getMinutes() < 10 ? '0' + today.getMinutes() : today.getMinutes()) + '';
		let s = today.getSeconds() < 10 ? '0' + today.getSeconds() : today.getSeconds();
		let fileName = h + m + s + "_" + parseInt(Math.random() * 10)
		return "ys/" + path + fileName
	},
}